<template>
    <el-card class="add-dish-card">
      <el-form :model="form" :rules="rules" ref="dishForm" @submit.native.prevent="submitDish">
        <el-form-item label="菜品名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入菜品名称..."
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="菜品图片" prop="imgUrl">
          <input type="file" @change="handleImageUpload" accept="image/*" />
          <div class="uploaded-image" v-if="form.imgUrl">
            <el-image :src="form.imgUrl" style="width: 100px; height: 100px; object-fit: cover;" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button :loading="isSubmitting" type="primary" @click="submitDish">提交菜品</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </template>
  
  <script setup lang="ts">
  import { ref,defineProps } from 'vue';
  import { ElCard, ElForm, ElFormItem, ElInput, ElButton, ElImage, ElMessage, ElLoading } from 'element-plus';
  import axios from 'axios';
  
  const props = defineProps({
    restaurantId: String,
  })
  interface DishForm {
    name: string;
    imgUrl: string | null;
  }
  
  const form = ref<DishForm>({
    name: '',
    imgUrl: null
  });
  
  const rules = {
    name: [
      { required: true, message: '请输入菜品名称', trigger: 'blur' },
      { min: 2, message: '菜品名称至少需要 2 个字符', trigger: 'blur' }
    ],
    imgUrl: [
      { required: true, message: '请上传菜品图片', trigger: 'change' }
    ]
  };
  
  const dishForm = ref();
  const isSubmitting = ref(false);
  
  const handleImageUpload = async (event: Event) => {
    const input = event.target as HTMLInputElement;
    if (input.files && input.files[0]) {
      const file = input.files[0];
  
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2; // 限制图片大小为2MB
  
      if (!isImage) {
        ElMessage.error('只允许上传图片文件。');
        return;
      }
  
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB。');
        return;
      }
  
      const formData = new FormData();
      formData.append('file', file);
  
      try {
        const loadingInstance = ElLoading.service({ text: '图片上传中...' });
        const response = await axios.post(`/file/upload/file`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        });
        loadingInstance.close();
  
        form.value.imgUrl = response.data.path;
        ElMessage.success('图片上传成功。');
      } catch (error) {
        ElMessage.error('图片上传失败，请重试。');
        console.error('Error uploading image:', error);
      }
    }
  };
  
  const submitDish = async () => {
    dishForm.value?.validate(async (valid: boolean) => {
      if (valid) {
        isSubmitting.value = true;
        const dishData = {
          name: form.value.name,
          imgUrl: form.value.imgUrl,
        };
  
        try {
          const response = await axios.post(    `/api/restaurants/${props.restaurantId}/recommendedDishes`, dishData);
          if (response.data.code === 200) {
            ElMessage.success('菜品提交成功');
            resetForm();
          } else {
            ElMessage.error(response.data.message || '菜品提交失败');
          }
        } catch (error) {
          console.error('提交菜品时出错:', error);
          ElMessage.error('菜品提交失败，请重试。');
        } finally {
          isSubmitting.value = false;
        }
      } else {
        ElMessage.error('请填写完整的菜品信息');
      }
    });
  };
  
  const resetForm = () => {
    form.value.name = '';
    form.value.imgUrl = null;
  };
  </script>
  
  <style scoped>
  .add-dish-card {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }
  
  .uploaded-image {
    margin-top: 10px;
  }
  </style>
  